import datetime
import json

from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.util import async_request as requests, constant
from loguru import logger
from com.arcfox.util import baidu_map_util
from com.arcfox.util import date
from com.arcfox.util import util
import sys

from com.arcfox.util.date import TimeUnit


class BaiduYiqingProceser:
    def __init__(self):
        pass

    async def save_baidu_yiqing_data(self, data_list):
        for data in data_list:
            select_sql = f"select * from af_baidu_risk_area where uid='{data['uid']}'"
            old_data = await db.query_all(select_sql)

            if old_data and (date.now() - old_data[0][17]).days == 0:
                logger.info(data['uid'] + " 一天内重复爬取")
                continue

            point = await self.convert_point(data["point"])
            location = await baidu_map_util.point2location(point)
            address = location.address
            province = location.province
            city = location.city
            district = location.district
            detail = await self.get_detail(data['uid'])
            detail_name = detail['poi_name']
            risk_time = date.date2str(date.get_future_date(date.now(), (-1) * data['icon_risk_day'], TimeUnit.DAY))

            hot_area = json.dumps(detail['poi_around_hot_area_list'])
            logger.info(data)
            logger.info(detail)
            with open("/tmp/data.txt", "a") as f:
                f.write(data['uid'] + "\t" + json.dumps(data) + "\n")
            with open("/tmp/detail.txt", "a") as f:
                f.write(data['uid'] + "\t" + json.dumps(detail) + "\n")

            select_sql = f"select * from af_baidu_risk_area where uid='{data['uid']}'"
            old_data = await db.query_all(select_sql)
            if old_data:
                sql = f"update af_baidu_risk_area set icon='{data['icon']}', icon_risk_day='{data['icon_risk_day']}',risk_time='{risk_time}' where uid='{data['uid']}'"
            else:
                sql = f"insert into af_baidu_risk_area(uid, location, icon, icon_risk_day, city_id,province,city,district, " \
                      f"address,poi_name,poi_hot_around_area,hot_around_area,patient_number,msg_source,risk_time) values ('{data['uid']}','{point}'," \
                      f"'{data['icon']}', '{data['icon_risk_day']}', '{data['city_id']}','{province}','{city}','{district}','{address}'," \
                      f"'{util.sql_param_pro(detail_name)}','{util.sql_param_pro(hot_area)}','{util.sql_param_pro(detail['hot_around_string'])}'," \
                      f"'{detail['patient_number']}','{util.sql_param_pro(detail['source'])}','{risk_time}')"

            await db.save_or_update(sql)

    async def save_sh_yiqing_data(self, data):

        point = await self.convert_point(data["location"])
        address = data["address"]
        province = "上海市"
        city = "上海市"
        arr = address.split('-')
        if len(arr) < 2:
            return
        district = arr[1]
        select_sql = f"select * from af_baidu_risk_area where uid='{data['uid']}'"
        old_data = await db.query_all(select_sql)
        risk_time = date.date2str(date.yesterday())
        if len(sys.argv) > 2:
            risk_time = sys.argv[2]
        if old_data:
            logger.info(data['uid'] + "已经存在")
            sql = f"update af_baidu_risk_area set icon=1, icon_risk_day=0,risk_time='{risk_time}' where uid='{data['uid']}'"
        else:
            sql = f"insert into af_baidu_risk_area(uid, location, icon, icon_risk_day, city_id,province,city,district, " \
                  f"address,poi_name,poi_hot_around_area,hot_around_area,patient_number,msg_source,risk_time) values ('{data['uid']}','{point}'," \
                  f"'0', '0', '289','{province}','{city}','{district}','{address}'," \
                  f"'{data['name']}','',''," \
                  f"'0','上海发布',{risk_time})"
        await db.save_or_update(sql)

    # https://api.map.baidu.com/geoconv/v1/?from=6&to=5&ak=99agH8dt1A3p39HBDIGQzPNRON8oiG89&coords=13499948.26,3653067.68
    async def convert_point(self, point):
        url = f"https://api.map.baidu.com/geoconv/v1/?from=6&to=5&ak={constant.BAIDU_MAP_AK}&coords={point}"
        try:
            response = await requests.get_with_session(url,
                                                       headers={
                                                           'Cookie': 'BAIDUID=4EBDB329AE7AF098EFD4043297CDDA23:FG=1'},
                                                       timeout=5)
            response_json = response.json()
            if response_json["status"] == 0:
                return f"{response_json['result'][0]['y']},{response_json['result'][0]['x']}"
        except Exception as e:
            logger.error(e)

    async def get_detail(self, uid):
        url = f"https://ugc.map.baidu.com/cube/ncp/areaInfo?poi_uid={uid}"
        try:
            response = await requests.get_with_session(url, timeout=5)
            response_json = response.json()
            if response_json["code"] == 0:
                return response_json["result"]
        except Exception as e:
            logger.error(e)
